<template>
  <el-dialog
    :title="!dataForm.id ? 'Create' : 'Modify'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="170px">
      <el-form-item label="userName" prop="userName">
        <el-input v-model="dataForm.userName" placeholder="User Name"></el-input>
      </el-form-item>
      <el-form-item label="password" prop="password" :class="{ 'is-required': !dataForm.id }">
        <el-input v-model="dataForm.password" type="password" placeholder="Password"></el-input>
      </el-form-item>
      <el-form-item label="comfirmPassword" prop="comfirmPassword" :class="{ 'is-required': !dataForm.id }">
        <el-input v-model="dataForm.comfirmPassword" type="password" placeholder="ComfirmPassword"></el-input>
      </el-form-item>
      <el-form-item label="email" prop="email">
        <el-input v-model="dataForm.email" placeholder="Email"></el-input>
      </el-form-item>
      <el-form-item label="mobile" prop="mobile">
        <el-input v-model="dataForm.mobile" placeholder="Mobile"></el-input>
      </el-form-item>
      <el-form-item label="role" size="mini" prop="roleIdList">
        <el-checkbox-group v-model="dataForm.roleIdList">
          <el-checkbox v-for="role in roleList" :key="role.roleId" :label="role.roleId">{{ role.roleName }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="status" size="mini" prop="status">
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="0">Disable</el-radio>
          <el-radio :label="1">Available</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">Cancel</el-button>
      <el-button type="primary" @click="dataFormSubmit()">Ok</el-button>
    </span>
  </el-dialog>
</template>

<script>
  // import { isEmail, isMobile } from '@/utils/validate'
  import {isEmail} from '@/utils/validate'
  export default {
    data () {
      var validatePassword = (rule, value, callback) => {
        if (!this.dataForm.id && !/\S/.test(value)) {
          callback(new Error('Password cannot be empty'))
        } else {
          callback()
        }
      }
      var validateComfirmPassword = (rule, value, callback) => {
        if (!this.dataForm.id && !/\S/.test(value)) {
          callback(new Error('Confirmation password cannot be empty'))
        } else if (this.dataForm.password !== value) {
          callback(new Error('Two inconsistent password input'))
        } else {
          callback()
        }
      }
      var validateEmail = (rule, value, callback) => {
        if (!isEmail(value)) {
          callback(new Error('Error in mailbox format'))
        } else {
          callback()
        }
      }
      // var validateMobile = (rule, value, callback) => {
      //   if (!isMobile(value)) {
      //     callback(new Error('手机号格式错误'))
      //   } else {
      //     callback()
      //   }
      // }
      return {
        visible: false,
        roleList: [],
        dataForm: {
          id: 0,
          userName: '',
          password: '',
          comfirmPassword: '',
          salt: '',
          email: '',
          mobile: '',
          roleIdList: [],
          status: 1
        },
        dataRule: {
          userName: [
            { required: true, message: 'User name cannot be empty', trigger: 'blur' }
          ],
          password: [
            { validator: validatePassword, trigger: 'blur' }
          ],
          comfirmPassword: [
            { validator: validateComfirmPassword, trigger: 'blur' }
          ],
          email: [
            { required: true, message: 'Mailbox cannot be empty', trigger: 'blur' },
            { validator: validateEmail, trigger: 'blur' }
          ]
          // mobile: [
          //   { required: true, message: '手机号不能为空', trigger: 'blur' },
          //   { validator: validateMobile, trigger: 'blur' }
          // ]
        }
      }
    },
    methods: {
      init (id) {
        this.dataForm.id = id || 0
        this.$http({
          url: this.$http.adornUrl('/sys/role/select'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          this.roleList = data && data.code === 0 ? data.list : []
        }).then(() => {
          this.visible = true
          this.$nextTick(() => {
            this.$refs['dataForm'].resetFields()
          })
        }).then(() => {
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/sys/user/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.userName = data.user.username
                this.dataForm.salt = data.user.salt
                this.dataForm.email = data.user.email
                this.dataForm.mobile = data.user.mobile
                this.dataForm.roleIdList = data.user.roleIdList
                this.dataForm.status = data.user.status
              }
            })
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        var _this = this
        _this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            _this.$http({
              url: _this.$http.adornUrl(`/sys/user/${!_this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: _this.$http.adornData({
                'userId': _this.dataForm.id || undefined,
                'username': _this.dataForm.userName,
                'password': _this.dataForm.password,
                'salt': _this.dataForm.salt,
                'email': _this.dataForm.email,
                'mobile': _this.dataForm.mobile,
                'status': _this.dataForm.status,
                'roleIdList': _this.dataForm.roleIdList
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                _this.$message.success('success', 1, function () {
                  _this.visible = false
                  _this.$emit('refreshDataList')
                })
              } else {
                _this.$message.error(data.msg, 1)
              }
            })
          }
        })
      }
    }
  }
</script>
